import { defineStore } from 'pinia'
import { store } from '@/store/index'
import { setItem, getItem } from '@/utils/storage'
import { USER } from '@/utils/contants'

interface IUser {
  id?: number;
  account?: string;
  head_pic?: string;
  pwd?: string;
  imgcode?: string;
}

interface UserInfo {
  user: { token: string } & IUser | null;
}

export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfo => {
    return {
      user: getItem<{ token: string } & IUser>(USER) // <{ token: string } & IUser> 这种写法是将token放进user的变量类型定义中【叫做接口字面量】
    }
  },
  getters: {}, // 可以将计算属性放在 getters 中使用，以便其在状态变化时产生
  actions: {
    setUser (val: { token: string } & IUser | null) {
      this.user = val
      // localStorage.setItem('user', JSON.stringify(state.user))
      // 优化后
      setItem(USER, this.user)
    }
  }
})

export function useUserInfoStoreWithOut () {
  return useUserInfoStore(store)
}
